import axios from 'axios'
import config from '@/config/index.js'
import tools from "@/utils/tools.js";

axios.defaults.baseURL = config.axios.BASE_URL
axios.defaults.timeout = config.axios.TIMEOUT


/**
 * 全局请求拦截器
 */
axios.interceptors.request.use((axiosRequestConfig) => {
    let token = tools.data.get(config.authentication.TOKEN_KEY);
    // VirAPI
    axiosRequestConfig.headers['app-token'] = config.axios.APP_KEY;
    if (token) {
        axiosRequestConfig.headers[config.authentication.TOKEN_NAME] = config.authentication.TOKEN_PREFIX + token;
    }
    if (!config.axios.REQUEST_CACHE && axiosRequestConfig.method == "get") {
        axiosRequestConfig.params = axiosRequestConfig.params || {};
        axiosRequestConfig.params["_t"] = new Date().getTime();
    }
    Object.assign(axiosRequestConfig.headers, config.axios.HEADERS);
    return axiosRequestConfig;
}, (error) => {
    return Promise.reject(error);
})

/**
 * 全局响应拦截器
 */
axios.interceptors.response.use((axiosResponse) => {
    if(axiosResponse.config.responseType === 'arraybuffer' || axiosResponse.config.responseType === 'blob'){
        return axiosResponse.data
    }
    if(axiosResponse.data.code === 200){
        return axiosResponse.data
    }

    window.$message.error(axiosResponse.data.msg)
}, (error) => {
    console.log(error)
})

// 自定义判断元素类型JS
function toType(obj) {
    return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

// 参数过滤函数
function filterNull(o) {
    for (var key in o) {
        if (o[key] === null) {
            delete o[key]
        }
        if (toType(o[key]) === 'string') {
            o[key] = o[key].trim()
        } else if (toType(o[key]) === 'object') {
            o[key] = filterNull(o[key])
        } else if (toType(o[key]) === 'array') {
            o[key] = filterNull(o[key])
        }
    }
    return o
}

/**
 * 接口处理函数
 */
function apiAxios(method, url, params, configs) {
    return new Promise((resolve, reject) => {
        if (params) {
            params = filterNull(params)
        }
        axios({
            method: method,
            url: url,
            data: method === 'POST' || method === 'PUT' ? params : null,
            params: method === 'GET' || method === 'DELETE' ? params : null,
            ...configs,
            withCredentials: false
        }).then(function (res) {
            resolve(res)
        }).catch(function (err) {
            reject(err)
        })
    })
}

/**
 * 导出在vue模板中的调用接口
 */
export default {
    get: function (url, params = {}, configs = {}) {
        return apiAxios('GET', url, params, configs)
    },
    post: function (url, params, configs) {
        return apiAxios('POST', url, params, configs)
    },
    put: function (url, params, configs) {
        return apiAxios('PUT', url, params, configs)
    },
    delete: function (url, params, configs) {
        return apiAxios('DELETE', url, params, configs)
    }
}